package org.zkoss.zk.ui;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.ceva.training.persistence.bo.User;
import org.ceva.training.persistence.dao.UsersDAO;
import org.ceva.training.util.constants.Constant;
import org.ceva.training.util.mail.SendMail;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;
import org.zkoss.zkplus.spring.SpringUtil;

public class RegisterWindow extends GenericForwardComposer {
	 private Textbox username;
	
	 public void onReset(){
			username.setValue("");			
		}
		
	 public	void onRegister(){
			String errorMsg = "";
			if(username.getValue()==null || username.getValue().trim().equals("")){
				errorMsg += "Username cannot be empty!\n";
			}						
			if(!errorMsg.equals("")){
				try {
					Messagebox.show(errorMsg,"Error",Messagebox.OK,Messagebox.ERROR);
				} catch (InterruptedException e) {				
					e.printStackTrace();
				}
			}else {
				onRegistering();
			}
		} 
	public void onBack(){
		//this.detach();
		Executions.sendRedirect("login.zul");		
	}
	
	public void onRegistering(){
		String strusername = username.getValue().trim();		
		User user = new User();
		user.setLoginname(strusername);		
		ApplicationContext ctx = SpringUtil.getApplicationContext();
		UsersDAO userDAO = (UsersDAO) ctx.getBean("UsersDAO");				
		
		List<User> list = userDAO.findByLoginname(user.getLoginname());
		if(list.isEmpty()){
			try {
				Messagebox.show("Username "+user.getLoginname()+" does not exist . please register first!","Forgot Password Failed",Messagebox.RETRY,Messagebox.INFORMATION);				
			} catch (InterruptedException e) {				
				e.printStackTrace();
			}		
		}else{
			try {
				Iterator<User> it = list.iterator();				
				while(it.hasNext()){
					user = it.next();								
				}		
			
				SendMail mailsender = (SendMail) ctx.getBean("mailService");
				mailsender.setTo(user.getEmail());
				mailsender.mailType(Constant.FORTGOTPASSWORD);
				Map<String, User> hashMail =new HashMap<String, User>();
				hashMail.put("user", user);
				mailsender.setSubject( "Password for training software");				
				mailsender.setEmailData(hashMail);			
				mailsender.sendMail();						
				Messagebox.show("Password is send to your mail account "+user.getEmail(),"Success",Messagebox.OK,Messagebox.INFORMATION);
				onBack();
			} catch (InterruptedException e) {				
				e.printStackTrace();
			}	
		}
	}
}
